/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.lock;


import com.inspur.edp.bef.api.be.BefLockType;
import com.inspur.edp.bef.api.be.IBEContext;
import com.inspur.edp.bef.core.session.FuncSession;
import com.inspur.edp.bef.core.session.FuncSessionManager;
import com.inspur.edp.bef.spi.entity.builtinimpls.BefModelResInfoImpl;
import com.inspur.edp.cef.api.RefObject;
import java.util.List;

public class LockService {

   private final FuncSession session;

   public LockService(FuncSession session) {
      this.session = session;
   }

   public static LockService getInstance() {
      return FuncSessionManager.getCurrentSession().getLockService();
   }

   //region AddLock

   /**
    * 新增锁
    */
   public void addLock(String beType, String dataId) {
      session.getFuncSessionItem(beType).getLockServiceItem().addLock(dataId);
   }

   /**
    * 新增锁
    */
   public final boolean addLocks(String beType, List<String> dataIds) {
      return session.getFuncSessionItem(beType).getLockServiceItem().addLocks(dataIds);
   }

   //endregion

   //region GetLockState
   /**
    * 获取加锁状态
    */
   public final boolean getLockState(String beType, String dataId, RefObject<String> userName) {
      return session.getFuncSessionItem(beType).getLockServiceItem().getLockState(dataId, userName);
   }
   //endregion

   //region ReleaseLock
   public final void releaseLocks(String beType) {
      session.getFuncSessionItem(beType).getLockServiceItem().releaseLocks();
   }

   public final void releaseAllLocks() {
      session.getBESessionItems().stream().forEach(item -> {
         item.getLockServiceItem().releaseLocks();
      });
   }

   //region tcc
   public String upgradeLock4Tcc(String beType) {
      return session.getFuncSessionItem(beType).getLockServiceItem().upgradeLock4Tcc();
   }

   public void releaseTccLock(String lockId) {
      LockAdapter.getInstance().releaseLock(lockId);
   }

   public void init4TccSecPhase(String beType, String groupId, List<String> dataIds) {
      session.getFuncSessionItem(beType).getLockServiceItem()
          .initLockState4TccSecondPhase(groupId, dataIds);
   }
   //endregion
  //endregion
}
